#include <set>

#include <QGuiApplication>
#include <QClipboard>

#include "SendPointHandlerBase.h"
#include "DistanceHandler.h"
#include "SelectHandler3D.h"
#include "Scene.h"
#include "QtOSGWidget.h"
#include "Qt3DPicker.h"
#include "CmdManager.h"

DistanceHandler::DistanceHandler()
	: m_snapPointFlag(0)
{
}

DistanceHandler::~DistanceHandler()
{
	auto scene = getScene();
	if (scene)
		scene->hideSnapPoint();
	auto sph = getSendPointHandler();
	if (sph)
	{
		sph->setSnapPointFlag(m_snapPointFlag);
		sph->setPointMask(m_pointMask);
	}
}

void DistanceHandler::input(const QVariant& data, const QString& rawInput, CommandSource cs)
{
	if (data.type() == QVariant::Bool && !data.toBool())
	{
		emit finished();
		return;
	}

	auto scene = getScene();
	auto sph = getSendPointHandler();
	if (status() == 0)
	{
		enableMouseHandler(MouseHandlerID::PointSender);
		if (sph)
		{
			sph->setPointMask(CS_LBTNDOWN | CS_MOUSEMOVE);
			m_snapPointFlag = sph->getSnapPointFlag();
			m_pointMask = sph->getPointMask();
			sph->setSnapPointFlag(SnapPointObject);
		}
		else
		{
			emit finished();
			return;
		}
		prompt(1, tr("起点坐标: "));
		return;
	}

	if (status() == 1)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			if (cs == CS_MOUSEMOVE)
			{
			}
			else
			{
				m_firstPoint = pt;
				prompt(2, tr("终点坐标: "));
			}
		}
		return;
	}

	if (status() == 2)
	{
		if (data.type() == QVariant::Vector3D)
		{
			auto pt = data.value<QVector3D>();
			if (cs == CS_MOUSEMOVE)
			{
			}
			else
			{
				output(pt);
				emit finished();
			}
		}
		return;
	}
}

void DistanceHandler::output(const QVector3D& pt)
{
	double distance = pt.distanceToPoint(m_firstPoint);
	auto dv = pt - m_firstPoint;
	QString rtext = QString("(dx = %1, dy = %2, dz = %3), dist = %4")
		.arg(dv.x(), 0, 'f', 4)
		.arg(dv.y(), 0, 'f', 4)
		.arg(dv.z(), 0, 'f', 4)
		.arg(distance, 0, 'f', 4);
	remark(rtext);
}
